package cn.maihe.elg.operation.initialization;

import cn.maihe.elg.operation.repository.entity.PermissionFuncDO;
import cn.maihe.elg.operation.repository.mapper.PermissionFuncMapper;
import cn.maihe.elg.operation.utils.DocFillUtil;
import cn.maihe.elg.operation.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author JHWei
 * 2018/7/27 上午10:06
 */
@Component
@Slf4j
public class LoadPermFuncMap implements CommandLineRunner {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private PermissionFuncMapper permissionFuncMapper;
    public static Map<Long, List<PermissionFuncDO>> permFuncMap = new HashMap<>();
    @Value("${simsunPath}")
    public String simsunPath;

    @Override
    public void run(String... args) {
        this.init();
        Path path = Paths.get(simsunPath);
        if (Files.notExists(path)|| StringUtil.isEmpty(simsunPath)) {
            throw new RuntimeException("查无此字体文件:" + simsunPath);
        }
        DocFillUtil.simsunPath = path.normalize().toString();
        log.info("已设置转换pdf所需字体文件：{}",path.normalize());
    }

    @Scheduled(fixedRate = 60 * 1000)
    public void init() {
        log.info("初始化获取权限菜单开始...");
        try {
            List<PermissionFuncDO> list = permissionFuncMapper.selectLists();
            if (list == null) {
                return;
            }
            permFuncMap = list.stream().collect(Collectors.groupingBy(PermissionFuncDO::getPermissionId));
        } catch (Exception e) {
            throw new RuntimeException("初始化权限菜单异常:" + e.getMessage(), e);
        }

    }
}
